package com.example.security.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.security.util.CustomResponseEntity;
import com.google.gson.Gson;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
  public JwtLoginFilter(AuthenticationManager authenticationManager) {
    super(authenticationManager);
  }

  private final Gson gson = new Gson();

  @Override
  protected void successfulAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain,
      Authentication authResult)
      throws IOException, ServletException {

    // 获取用户名及权限信息
    String username = ((UserDetails) authResult.getPrincipal()).getUsername();

    List<String> roles = new ArrayList<>();
    authResult.getAuthorities().forEach(a -> roles.add(a.getAuthority()));

    // 生成token
    String token =
        JWT.create()
            .withSubject(username)
            .withClaim("roles", roles)
            .withExpiresAt(new Date(System.currentTimeMillis() + 6 * 3600 * 1000))
            .sign(Algorithm.HMAC512("MY-JWT".getBytes()));

    var r = new HashMap<String, Object>();
    r.put("code", 0);
    r.put("msg", "登录成功");
    r.put("token", "Bearer " + token);
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json, charset=utf-8");
    response.getWriter().write(gson.toJson(r));
  }

  @Override
  protected void unsuccessfulAuthentication(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
      throws IOException, ServletException {

    CustomResponseEntity.toJson(response, HttpStatus.OK.value(), -3, "用户名或密码不正确");
  }
}
